package org.eli.material;

import org.eli.*;
import org.eli.HitRecord;

/**
 * 只会发生折射的绝缘体材质
 */
public class Dielectric implements Material {

    // 光密介质的折射指数和光疏介质的折射指数的比值
    private double refIndex;

    public Dielectric(double ri) {
        this.refIndex = ri;
    }

    @Override
    public boolean scatter(Ray rIn, HitRecord rec, Vec3 attenuation, Ray scattered) {
        attenuation.e = new Vec3(1.0, 1.0, 1.0).e;
        double etaiOverEtat = rec.frontFace ? 1.0 / refIndex : refIndex;

        Vec3 unitDirection = Main.unitVector(rIn.direction());
        double cosTheta  = RtWeekend.ffmin(rec.normal.dot(unitDirection.negate()), 1.0);
        double sinTheta = Math.sqrt(1.0 - cosTheta*cosTheta);
        if (etaiOverEtat * sinTheta > 1.0 ) {
            Vec3 reflected = Vec3.reflect(unitDirection, rec.normal);
            scattered.setOrigin(rec.p);
            scattered.setDirection(reflected);
            return true;
        }

        double reflectProb  = RtWeekend.schlick(cosTheta, etaiOverEtat);
        if (RtWeekend.randomDouble() < reflectProb) {
            Vec3 reflected = Vec3.reflect(unitDirection, rec.normal);
            scattered.setOrigin(rec.p);
            scattered.setDirection(reflected);
            return true;
        }

        Vec3 refracted = Vec3.reflect(unitDirection, rec.normal, etaiOverEtat);
        scattered.setOrigin(rec.p);
        scattered.setDirection(refracted);

        return true;
    }

    public double getRefIndex() {
        return refIndex;
    }
}
